package com.qf.zuoye0620.filter;

import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/20 18:58
 * @Version v1.8
 **/
public class RequiredParamFilter implements Filter {
    private static final String MERCHANT_ID_PARAM = "mch_id";
    private static final String APP_ID_PARAM = "appid";
    private static final String TOKEN_PARAM = "token";
    private static final String SIGN_PARAM = "sign";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

        String merchantId = httpRequest.getParameter(MERCHANT_ID_PARAM);
        String appId = httpRequest.getParameter(APP_ID_PARAM);
        String token = httpRequest.getParameter(TOKEN_PARAM);
        String sign = httpRequest.getParameter(SIGN_PARAM);

        if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(appId) ||
                StringUtils.isEmpty(token) || StringUtils.isEmpty(sign)) {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setStatus(HttpStatus.BAD_REQUEST.value());
            httpResponse.getWriter().println("Missing required parameters");
            return;
        }

        // 所有参数都存在，继续处理请求
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
